/*
 * @Author: your name
 * @Date: 2021-12-08 18:02:55
 * @LastEditTime: 2021-12-13 10:09:28
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \react-template\src\components\RouteChunk\index.tsx
 */
import { Tag } from "antd";
import React, { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { _findRouteByLocation } from "../../utils";
import "./index.less";


const RouteChunk = (): React.ReactElement => {
	const [routeList, setRouterList] = useState<any>([]);
	const location = useLocation();
	const navigate = useNavigate();

	const routeChange = (item) => {
		navigate(item.path);
	};
	const closeNav = async (e, index) => {
		const arr = [...routeList];
		console.log(arr);
		if (arr.length > 1) {
			await setRouterList(arr.splice(index));
			sessionStorage.setItem("ROUTE_CHUNKS", JSON.stringify(arr));
			navigate(routeList[0].path);
		} else {
			e.preventDefault();
		}
	};
	useEffect(() => {
		const RouteChunk = sessionStorage.getItem("ROUTE_CHUNKS");
		let Routes = [];
		if (RouteChunk && RouteChunk !== "") {
			Routes = JSON.parse(RouteChunk);
			setRouterList(Routes);
		} else {
			const routes = _findRouteByLocation(location.pathname);
			const arr = [...routes];
			setRouterList(arr);
			sessionStorage.setItem("ROUTE_CHUNKS", JSON.stringify(arr));
		}
		console.log("sessionStro", RouteChunk);
	}, [location.pathname]);
	return <div className="route_chunk_box">
		{
			routeList && routeList.length && routeList.map((item, index) => {
				return <Tag onClose={(e) => { closeNav(e, index); }} onClick={() => { routeChange(item); }} color={location.pathname === item.path ? "#108ee9" : ""} closable key={item.path}>{item.title}</Tag>;
			})
		}
	</div >;
};

export default RouteChunk;